package ma.myschool.app.webapp.action;

import java.io.Serializable;

import ma.myschool.app.model.AnneeScolaire;
import ma.myschool.app.service.AnneeScolaireManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;

@Component("anneeScolaireForm")
@Scope("request")
public class AnneeScolaireForm extends BasePage implements Serializable {
    private AnneeScolaireManager anneeScolaireManager;
    private AnneeScolaire anneeScolaire = new AnneeScolaire();
    private Long id;

    @Autowired
    public void setAnneeScolaireManager(@Qualifier("anneeScolaireManager") AnneeScolaireManager anneeScolaireManager) {
        this.anneeScolaireManager = anneeScolaireManager;
    }

    public AnneeScolaire getAnneeScolaire() {
        return anneeScolaire;
    }

    public void setAnneeScolaire(AnneeScolaire anneeScolaire) {
        this.anneeScolaire = anneeScolaire;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String delete() {
    	try{
	    	id = getParameter("id") != null ? new Long(getParameter("id")) : null;
	        anneeScolaireManager.remove(id);
	        addMessage("anneeScolaire.deleted");
    	} catch (DataIntegrityViolationException e) {
			addError(getText("errors.use.already"));
		}  
	      
        return "success";
    }

    public String edit() {
        // Workaround for not being able to set the id using #{param.id} when using Spring-configured managed-beans
        if (id == null) {
        	id = getParameter("id") != null ? new Long(getParameter("id")) : null;
        }
        // Comparison to zero (vs. null) is required with MyFaces 1.2.2, not with previous versions
        if (id != null && id != 0) {
            anneeScolaire = anneeScolaireManager.get(id);
        } else {
            anneeScolaire = new AnneeScolaire();
        }

        return "editAnneeScolaire";
    }

    public String save() {
        boolean isNew = (anneeScolaire.getId() == null || anneeScolaire.getId() == 0);
        anneeScolaireManager.save(anneeScolaire);

        String key = (isNew) ? "anneeScolaire.added" : "anneeScolaire.updated";
        addMessage(key);

        if (isNew) {
            return "list";
        } else {
            return "edit";
        }
    }
} 